home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: nntp.coast.net!torn!news!apollo!saed
- From: saed@engn.uwindsor.ca (Saed Aryan)
- Subject: Re: friend functions and access to private variables...
- X-Nntp-Posting-Host: apollo.engn.uwindsor.ca
- Message-ID: <Dnyy92.MLL@news.uwindsor.ca>
- Keywords: friend
- Sender: news@news.uwindsor.ca (Usenet)
- Reply-To: saed@engn.uwindsor.ca
- Organization: VLSI Research Group - University of Windsor
- Date: Fri, 8 Mar 1996 21:55:50 GMT
-
- Hi all,
-
- Dariusz Piatkowski asked:
- >I'm dealing with two classes, where a member function of class A is declared as
- >a friend function of class B.
- >Unfortunately this does not allow the friend function access to private variables in
- >class B...what gives? Is it not legal to make such a declaration?
-
- well, I guess you're right!
-
- --- A friend method of a non friend class has no access to the private member data.
- Apparently the class to which that method belongs must be a friend. The friend
- declaration of that method is then redundant.
-
- The code snippet below (compilable) will show what works and what doesn't.
-
- Aryan.
-
- //---- begin code
- class X {
- friend void yMethod(X x);
- friend void aFunction(X x);
- friend class Z;
- private: int a;
- };
-
- void aFunction(X x){x.a=1;};
- // okay: aFunction is friend of class X and may access private member 'a' of X
-
- class Z { public: void zMethod(X x){x.a=1;}; };
- // okay: class Z is friend of X, zMethod may access private member 'a' of X
-
- class Y { public: void yMethod(X x){x.a=1;}; };
- // error: member `a' is a private member of class `X' (class Y is not a friend)
- // this is Dariusz's question
-
- void aFunction(X x, int i){ return x.a=1; };
- // error: member `a' is a private member of class `X'
- // (different signature, not a friend)
-
- main(){}
- //---end of code
-
-
-